import { StyleSheet, Text, View, Keyboard, InteractionManager } from 'react-native'
import React, { useState, useCallback, useEffect, createRef } from 'react'
import { useFocusEffect } from '@react-navigation/native'
import axios from '../axios'
import { Avatar, ScrollView, TextArea, Button } from 'native-base'
import { connect } from 'react-redux'
import { getDomain } from '../utils/tools'
import { useSocket } from '../hook/useSocket'
import { sendMsgSuccessAction, resetUnreadMsgAction } from '../redux/actionCreator/chat'

const ChatWindow = ({ navigation, route, user, onlineMsg, sendMsgSuccessAction, resetUnreadMsgAction }) => {
  console.log('route.params', route.params)
  console.log('user', user)

  const { id, name } = route.params
  const [list, setList] = useState([])
  const [content, setContent] = useState('')
  const scrollView = createRef(null)

  const toBottom = () => {
    scrollView?.current?.scrollToEnd()
  }

  const socket = useSocket()
  useEffect(() => {
    const a = Keyboard.addListener("keyboardDidShow", _keyboardDidShow);
    console.log('a', a)
    const b = Keyboard.addListener("keyboardDidHide", _keyboardDidHide);

    // cleanup function
    return () => {
      a.remove()
      b.remove()
    };
  }, []);
  const _keyboardDidShow = () => {
    console.log('_keyboardDidShow')
    toBottom()
  }
  const _keyboardDidHide = () => {
    console.log('_keyboardDidHide')
  }
  useFocusEffect(
    useCallback(() => {
      // Do something when the screen is focused
      console.log('路由进来了')
      navigation.setOptions({
        title: name
      })
      socket.emit('enter', {
        fromUser: user._id,
        toUser: id
      })
      resetUnreadMsgAction(id)
      return () => {
        // Do something when the screen is unfocused
        // Useful for cleanup functions
        console.log('路由离开了')
        socket.emit('leave', {
          fromUser: user._id,
          toUser: id
        })
      };
    }, [])
  )
  const success = useCallback((data) => {
    // 收到服务器推送的消息，可以跟进自身业务进行操作
    console.log('success：', data);
    // 成功发送，清空输入框
    setContent('')
    console.log('list', list)
    setList([...list, data])
    sendMsgSuccessAction(data)
    // 去底部,无反应
    setTimeout(() => {
      toBottom()
    })
  }, [list, sendMsgSuccessAction])
  useEffect(() => {
    socket.on('success', success)
    return () => socket.off('success')
  }, [socket, success])

  useEffect(() => {
    axios.get(`/chat/${id}`).then(res => {
      console.log('获取数据成功', res)
      setTimeout(() => {
        setList(res.data)
        scrollView.current?.scrollToEnd()
      })
    }).catch(err => {
      console.log('获取数据失败', err)
    })
  }, [id])

  useEffect(() => {
    if (list.some(item => item._id === onlineMsg._id)) return
    setList([...list, onlineMsg])
  }, [onlineMsg])

  const isSelf = (id) => {
    return id === user._id
  }

  const onChangeText = (val) => {
    console.log(val)
    setContent(val)
  }
  const send = () => {
    socket.emit('chat', {
      fromUser: user._id,
      toUser: id,
      content: content,
      // isRead: true
    })
    console.log('send')
  }
  const onFocus = () => {
    console.log('onFocus')
  }
  return (
    <View style={styles.container}>
      <ScrollView style={styles.list} ref={scrollView}>
        {
          list.map(item => {
            return (
              <View style={[styles.item, isSelf(item.fromUser._id) && styles.right]} key={item._id}>
                {
                  isSelf(item.fromUser._id) ?
                    <>
                      <View style={styles.main}>
                        <View style={[styles.contentBox, isSelf(item.fromUser._id) && styles.rightBox]}>
                          <Text style={styles.pad}>{item.content}</Text>
                        </View>
                        <Text style={styles.note}>{item.isRead ? '已读' : '未读'}</Text>
                      </View>
                      <Avatar size="48px" source={{
                        uri: getDomain(item.fromUser.avatar)
                      }} />
                    </>
                    :
                    <>
                      <Avatar size="48px" source={{
                        uri: getDomain(item.fromUser.avatar)
                      }} />
                      <View style={styles.main}>
                        <View style={[styles.contentBox, styles.left]}>
                          <Text style={styles.pad}>{item.content}</Text>
                        </View>
                      </View>
                    </>
                }

              </View>
            )
          })
        }
      </ScrollView>
      <View style={styles.fixBottom}>
        <View style={styles.textArea}>
          <TextArea value={content} onChangeText={onChangeText} onFocus={onFocus}></TextArea>
        </View>
        <Button onPress={send} style={[!content && { backgroundColor: 'gray' }]}>发送</Button>
      </View>
    </View>
  )
}

export default connect((state) => {
  return {
    user: state.userReducer,
    onlineMsg: state.chatReducer.onlineMsg
  }
}, {
  sendMsgSuccessAction,
  resetUnreadMsgAction
})(ChatWindow)

const h = 80
const styles = StyleSheet.create({
  container: {
    flex: 1,
    // paddingBottom: h
  },
  list: {
    display: 'flex',
    // flex: 1
  },
  fixBottom: {
    flexDirection: 'row',
    // flex: 1
  },
  item: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 15
  },
  main: {
    maxWidth: '80%',
    marginHorizontal: 5
  },
  note: {
    // backgroundColor: 'red',
    textAlign: 'right',
    fontSize: 12
  },
  contentBox: {
    borderRadius: 6,

  },
  pad: {
    marginHorizontal: 20,
    paddingVertical: 10,
    color: 'white'
  },
  left: {
    backgroundColor: 'green',
  },
  right: {
    justifyContent: 'flex-end',
  },
  rightBox: {
    backgroundColor: 'blue',
  },
  textArea: {
    flex: 1,
    maxHeight: 100
  }
})